package com.study.zouchao.superproject.modifyuserinfo.view.fragment;

import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.icu.text.BreakIterator;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.study.zouchao.superproject.R;
import com.study.zouchao.superproject.base_zou.MyBaseFragment;
import com.study.zouchao.superproject.base_zou.ZouImgLoader;
import com.study.zouchao.superproject.login.model.entity.User;
import com.study.zouchao.superproject.modifyuserinfo.contract.IModifyUserInfoContract;
import com.study.zouchao.superproject.modifyuserinfo.model.dto.SelectCityDTO;
import com.study.zouchao.superproject.modifyuserinfo.presenter.ModifyUserInfoPresenter;
import com.study.zouchao.superproject.util.DialogUtil;
import com.study.zouchao.superproject.util.EventBusEvent;
import com.study.zouchao.superproject.util.EventBusEvent_C;
import com.study.zouchao.superproject.util.EventBusUtils;
import com.study.zouchao.superproject.util.LogLongUtil;
import com.study.zouchao.superproject.util.StringUtils;
import com.study.zouchao.superproject.util.ToastUtils;
import com.study.zouchao.superproject.util.ui.citypicker.cascade.activity.CityPickerActivity;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * Created by Administrator on 2017/1/29.
 */

public class ModifyUserInfoFragment extends MyBaseFragment implements IModifyUserInfoContract.IModifyUserInfoView {
    //头像
    @BindView(R.id.id_modify_head_img)
    ImageView mHeadImg;

    //头像点击区域
    @BindView(R.id.id_ll_modify_head_img)
    LinearLayout mLlHeadImg;

    //昵称
    @BindView(R.id.id_edit_nickname)
    EditText mEditNickName;

    //性别单选按钮组
    @BindView(R.id.id_radio_group_sex)
    RadioGroup mRgSex;

    //单选 男
    @BindView(R.id.id_rb_man)
    RadioButton mRbMan;

    //性别 女
    @BindView(R.id.id_rb_woman)
    RadioButton mRbWoman;

    //性别 保密
    @BindView(R.id.id_rb_other)
    RadioButton mRbOther;

    //地区
    @BindView(R.id.id_location)
    TextView mTvLocation;

    //一句话描述
    @BindView(R.id.id_edit_resume)
    EditText mEditResume;

    //出生年月
    @BindView(R.id.id_edit_birthday)
    TextView mEditBirthday;

    //确认更改
    @BindView(R.id.id_btn_modify_sure)
    Button mBtnSure;
    //presenter
    private IModifyUserInfoContract.IModifyUserInfoPresenter mPresenter;

    private String mUserName;
    @Override
    protected View getLoadingTargetView() {
        return getCurrentFragmentRootView().findViewById(R.id.id_layout_modify_user_info);
    }

    @Override
    protected int getFragmentLayoutID() {
        return R.layout.final_fragment_modify_user_info;
    }

    /*
     * MVP
     */
    @Override
    public void showBaseLoading(boolean isShow) {
        if (isShow) {
            showLoading("");
        } else {
            hideLoading();
        }
    }

    @Override
    public void setNickname(String nickname) {
        mEditNickName.setText(nickname);
    }

    @Override
    public void setSex(String sex) {
        switch (sex) {
            case "男" :
                mRbMan.toggle();
                break;
            case "女" :
                mRbWoman.toggle();
                break;
            default:
                mRbOther.toggle();
                break;
        }
    }

    @Override
    public void setResume(String resume) {
        mEditResume.setText(resume);
    }

    @Override
    public void setBirthday(String birthday) {
        mEditBirthday.setText(birthday);
    }

    @Override
    public void loadHeadImg(String urlImg) {
//        LogLongUtil.logD("陈宫上传图片",urlImg);
        ZouImgLoader.loadImage(getContext(), mHeadImg, urlImg, R.drawable.user);
    }

    @Override
    public void setLocation(String location) {
        mTvLocation.setText(location);
    }

    /*
     * 修改完成后 finish掉当前Activity
     */
    @Override
    public void finishCurrentModifyUserActivity() {
        if (getActivity() != null) getActivity().finish();
    }

    @Override
    public void showNicknameError(String msg) {
        mEditNickName.setError(msg);
    }

    @Override
    public void showResumeError(String msg) {
        mEditResume.setError(msg);
    }

    @Override
    public void initInfos(User user) {
        if (user==null || StringUtils.isEmpty(user.getUserName()))   return;
        mUserName = user.getUserName();
    }


    /*
     * 当点击头像时弹出一个选项框选择是从哪里取图片
     */
    @Override
    public void showChoosePicDialog() {
        String title = "设置头像";
        String[] items = {"选择本地图片", "拍照"};
        DialogUtil.showItemAlertDialog(getContext(), title, items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mPresenter.clickChoosePicDialog(which);
            }
        });
    }

    /*
     * 监听器
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    @OnClick({R.id.id_btn_modify_sure, R.id.id_ll_modify_head_img, R.id.id_edit_birthday, R.id.id_location})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.id_btn_modify_sure :
                clickModifySure();
                break;
            case R.id.id_ll_modify_head_img :
                showChoosePicDialog();
                break;
            case R.id.id_edit_birthday :
//                showCitiesPicker();
//                showDatePickerDialog();
                break;
            case R.id.id_location :
                gotoCitiesPickerActivity();
                break;
        }
    }

    private void gotoCitiesPickerActivity() {
        if (StringUtils.isEmpty(mUserName)) return;
        CityPickerActivity.actionStartCityPickerActivity(getActivity(), mUserName);
    }


    /**
     * 显示日期选择器
     */
    private void showDatePickerDialog() {
        new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                //选择日期后显示出来
                mEditBirthday.setText(year+"-"+(month+1)+"-"+dayOfMonth);
            }
        }, 2016, 1, 1).show();
    }

    private void clickModifySure() {
        String nickname = mEditNickName.getText().toString().trim();
        String sex = getSelectedSex();
        String birthday = mEditBirthday.getText().toString().trim();
        String location = mTvLocation.getText().toString().trim();
        mPresenter.confirmModify(nickname, sex, location);
    }

    /**
     * 得到单选框中被选中的性别
     * @return
     */
    private String getSelectedSex() {
        switch (mRgSex.getCheckedRadioButtonId()) {
            case R.id.id_rb_man :
                return "男";
            case R.id.id_rb_woman :
                return "女";
            default:
                return "保密";
        }
    }

    /*
     * 生命周期
     */
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mPresenter = new ModifyUserInfoPresenter(getContext(), this);
        EventBusUtils.register(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventBusEvent event) {
        switch (event.getTag()) {
            case EventBusEvent_C.EVENT_SELECT_CITY :
                receiveSelectCity(event);
                break;
        }
    }

    private void receiveSelectCity(EventBusEvent event) {
        SelectCityDTO dto = (SelectCityDTO) event.getObj();
        if (StringUtils.isEmpty(mUserName)) return;
        if (dto == null)    return;
        if (mUserName.equals(dto.userName)) {
            mTvLocation.setText(dto.city);
        }
    }

    /**
     * 拍照完成后回调
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        //这个super不能落下 否则可能回调不了
        super.onActivityResult(requestCode, resultCode, data);
        //处理resultCode
        mPresenter.judgeActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onDestroy() {
        //在这里销毁Presenter 防止内存泄漏
        mPresenter.onDestoryPresnter();
        super.onDestroy();
        EventBusUtils.unRegister(this);
    }
}
